//#ifndef MINGW

// MSVC header
#include "stdafx.h"

//#endif

#include "keybconf.h"

bool readKeyboardConfig(std::vector<KB_Struct> &switchCases)
{
    switchCases.clear();

    HKEY rootKey = 0;
    long res = RegOpenCurrentUser(KEY_READ, &rootKey);
    if (res != ERROR_SUCCESS)
        return false;

    HKEY key = 0;
    res = RegOpenKeyEx(rootKey, _T("Software\\Sintegrial\\KeySwitch"), 0, KEY_READ, &key);
    if (res != ERROR_SUCCESS)
    {
        RegCloseKey(rootKey);
        return false;
    }

    BYTE value[1024];
    DWORD type = REG_BINARY;
    DWORD len = sizeof(value);

    TCHAR name[20];
    int cnt = 1;
    UINT *ptr;

    do {
        // get value
        wsprintf(name, _T("Layout%d"), cnt++);
        len = sizeof(value);
        res = RegQueryValueEx(key, name, NULL, &type, value, &len);
        if (res != ERROR_SUCCESS)
            break;

        if (!len) continue;

        // parse value
        KB_Struct kbs;
        ptr = (UINT*)value;
        kbs.keyCode = *ptr++;

        int i = 4;
        while (i < len) {
            i += 4;
            kbs.layouts.push_back(*ptr++);
        }

        if (!kbs.layouts.empty())
            switchCases.push_back(kbs);

    } while (true);

    RegCloseKey(key);
    RegCloseKey(rootKey);
    return true;
}

bool writeKeyboardConfig(const std::vector<KB_Struct> &switchCases)
{
  HKEY rootKey = 0;
  long res = RegOpenCurrentUser(KEY_WRITE, &rootKey);
  if (res != ERROR_SUCCESS)
      return false;

  HKEY key = 0;

  SECURITY_ATTRIBUTES sattr;
  sattr.nLength = sizeof(SECURITY_ATTRIBUTES);
  sattr.lpSecurityDescriptor = NULL;
  sattr.bInheritHandle = TRUE;

  res = RegCreateKeyEx(rootKey, _T("Software\\Sintegrial\\KeySwitch"), 0, NULL,
                       REG_OPTION_NON_VOLATILE, KEY_WRITE, &sattr, &key, NULL);
  if (res != ERROR_SUCCESS)
  {
      RegCloseKey(rootKey);
      return false;
  }

  DWORD type = REG_BINARY;
  DWORD len;

  TCHAR name[20];
  UINT buffer[200];

  int cnt;
  for (cnt = 0; cnt < switchCases.size(); cnt++)
  {
      // prepare value
      KB_Struct kbs = switchCases.at(cnt);
      buffer[0] = kbs.keyCode;
      int i;
      for (i = 0; i < kbs.layouts.size(); i++)
      {
        buffer[i+1] = kbs.layouts.at(i);
      }
      buffer[i+1] = 0;

      // set value
      wsprintf(name, _T("Layout%d"), cnt+1);
      len = i*4+4;

      res = RegSetValueEx(key, name, 0, type, (BYTE*)buffer, len);
//      if (res != 0)
//      {
//        // error
//        RegCloseKey(key);
//        RegCloseKey(rootKey);
//        return false;
//      }
  }

  // cleanup more layouts if present
  do {
    wsprintf(name, _T("Layout%d"), ++cnt);
    res = RegDeleteValue(key, name);
  } while (res == ERROR_SUCCESS);

  RegCloseKey(key);
  RegCloseKey(rootKey);
  return true;
}
